package com.share.dymamic.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.share.dymamic.annotion.DBWrite;
import com.share.dymamic.datasource.DataSourceContextHolder;

/**
 * 将被@DBWrite注解的方法的数据源设置为只写数据源
 * @author lenovo
 *
 */
public class DBWriteInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(DBWriteInterceptor.class);

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
			try {
				if(handler instanceof HandlerMethod){
					HandlerMethod handlerMethod = (HandlerMethod) handler;
					DBWrite annotation = handlerMethod.getMethodAnnotation(DBWrite.class);
					if(annotation != null){
						DataSourceContextHolder.setDataSource(DataSourceContextHolder.DB_TYPE_W);
					}
				}else{
					return true;
				}
			} catch (Exception e) {
				logger.debug("switch to DB_TYPE_W failed:"+e.getMessage());
			}
			return true;
		}
	
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
		try {
			DataSourceContextHolder.setDataSource(DataSourceContextHolder.DB_TYPE_R);
		} catch (Exception e) {
			logger.debug("switch to DB_TYPE_R failed:"+e.getMessage());
		}
		
	}
}
